/**
 * 数据管理=>用量查询
 */
import * as React from "react";
import {Spin,Button,Modal, message} from "antd";
import IconFont from "../../../../assets/ICON";
import CalcCondition, {CalcConditionParam} from "./compontents/Condition";
import "./index.less";
import DataCalcTable from "./compontents/ConditionTable";
import moment from "moment";
import { AjaxData } from "../../../../data/interface/publicInterface";
import { getEnergySummaryData,getEnergyMonthData } from "../ServeApi";
import ExportJsonExcel from 'js-export-excel';
export interface CalcCodeProps {}

export interface CalcCodeState {}

class CalcCode extends React.Component<CalcCodeProps, CalcCodeState> {
    private paramJson: CalcConditionParam = {
        energyType: 1,
        buildId: "",
        timeType: 2,
        startData: "0",
        endData: "0"
    };
    private dataSouce: any = null;
    private columns: any[] = [
      {
        title: "名称",
        width: 100,
        dataIndex: "name",
        key: "name",
        fixed: "left",
      },
    ];
    private mode:string = "sum"
    state = {resultVisible: false,loading:false};
    
    render() {
        return (
            <div className="calcCode">
                <CalcCondition
                  onChange={(paramJson: CalcConditionParam) => {
                    console.log("改变的",paramJson)
                    this.paramJson = paramJson;
                  }}
                  query={(paramJson: CalcConditionParam ,mode:string) => {
                    this.query(paramJson,mode);
                  }}
                />
                <div className="subject">
                    <div className="operation">
                        
                        <Button type="primary" className="export" size="middle"
                                icon={<IconFont type="icon_daochu"/>}
                                onClick={()=>{this.exportDeviceCalc();}}
                        >
                            导出
                        </Button>
                        
                    </div>
                    <Spin spinning={this.state.loading}>
                    <DataCalcTable 
                      columns={this.columns}
                      dataSouce={this.dataSouce}
                    />
                    </Spin>
                </div>
            </div>
        );
    }
    //查询
    query(paramJson: CalcConditionParam,mode:string) {
        if (paramJson.startData === '0' || paramJson.endData=== '0') {
          message.info("请选择时间！");
        } else {
          let {energyType,buildId,timeType,startData,endData}= paramJson;
            startData = moment(Number(startData)).format("YYYY-MM-DD HH:mm:ss");
            endData = moment(Number(endData)).format("YYYY-MM-DD HH:mm:ss");
          this.paramJson = {
            energyType,buildId,timeType,startData,endData
          }
          this.mode = mode
          if(mode==="sum"){
            this.getSumData(this.paramJson)
          }else{
            this.getMonthData(this.paramJson)
          }
          this.forceUpdate();
        }
    }
    /**数据请求 */
  //用量汇总或者月
    async getSumData(pream: any) {
      let _this = this;
      try {
        _this.setState({ loading: true });
        let res: any = await getEnergySummaryData(JSON.stringify(pream)).catch((err) => {
          _this.setState({ loading: false });
        });
        let json: AjaxData = res;
        if (json.success) {
          _this.modeSumTableDataGo(json.data);
          _this.setState({ loading: false });
          _this.forceUpdate();
        } else {
          Modal.error({
            title: json.message,
            onOk: () => {
              _this.setState({ loading: false });
            },
          });
        }
      } catch (error) {
        Modal.error({
          title: "初始化程序失败，无法读取数据，请刷新页面。",
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
        console.error(error);
      }
    }
    async getMonthData(pream: any) {
      let _this = this;
      try {
        _this.setState({ loading: true });
        let res: any = await getEnergyMonthData(JSON.stringify(pream)).catch((err) => {
          _this.setState({ loading: false });
        });
        let json: AjaxData = res;
        if (json.success) {
          _this.modeMonthTableDataGo(json.data);
          _this.setState({ loading: false });
          _this.forceUpdate();
        } else {
          Modal.error({
            title: json.message,
            onOk: () => {
              _this.setState({ loading: false });
            },
          });
        }
      } catch (error) {
        Modal.error({
          title: "初始化程序失败，无法读取数据，请刷新页面。",
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
        console.error(error);
      }
    }
    //汇总处理
    modeSumTableDataGo(data){
      //1.Columns生成
      this.columns = [
        {
          title: "设备名称",
          width: 100,
          dataIndex: "name",
          key: "name",
        },
        {
          title: "设备位号",
          width: 100,
          dataIndex: "no",
          key: "no",
        },
        {
          title: "起始时间",
          width: 100,
          dataIndex: "startData",
          key: "startData",
        },
        {
          title: "起始表码",
          width: 100,
          dataIndex: "minDate",
          key: "minDate",
        },
        {
          title: "截止时间",
          width: 100,
          dataIndex: "endDate",
          key: "endDate",
        },
        {
          title: "截止表码",
          width: 100,
          dataIndex: "maxDate",
          key: "maxDate",
        },
        {
          title: "ct*pt",
          width: 100,
          dataIndex: "cpt",
          key: "cpt",
        },
        {
          title: "电量",
          width: 100,
          dataIndex: "val",
          key: "val",
        }
      ]
      this.dataSouce = data
      this.forceUpdate()
    }
    //月处理
    modeMonthTableDataGo(data){
      let datas:any[] = data.data;
      let monthlyDate:any[] = data.monthlyDate;
      this.columns = [
        {
          title: "设备名称",
          width: 100,
          dataIndex: "name",
          key: "name",
          fixed: "left"
        },
        {
          title: "设备位号",
          width: 100,
          dataIndex: "no",
          key: "no",
          fixed: "left"
        }
      ];
      monthlyDate.map((item: any, index: number)=>{
        let col = {
            title: item,
            dataIndex: "Column" + index,
            key: "Column" + index,
            width: 150,
        }
        this.columns.push(col);
        return col;
      })
      let huizong:any = {
        no:"汇总"
      }
      let dataSouce: any[] = datas.map((item: any,num:number)=>{
        let arrData = item.monthVal;
        let obj = {};
        arrData.map((jtem: any, index: number) => {
          // aa[index] = aa[index]?aa[index]+jtem.val:jtem.val;
          huizong["Column" + index] =  huizong["Column" + index]? huizong["Column" + index]+jtem.val:jtem.val;
          obj["Column" + index] = jtem.val;
          return jtem;
        });
        
        let newObj = {};
        Object.assign(newObj, obj, item);
        return newObj;
      })
      dataSouce.push(huizong)
      this.dataSouce = dataSouce
      this.forceUpdate()
    }
    //表码导出
    exportDeviceCalc() {
      
      let datas = this.dataSouce?this.dataSouce:''
      
      let sheetFilter:any[] = [];
      let sheetHeader:any[] = []
      this.columns.map((item:any)=>{
        sheetFilter.push(item.key);
        sheetHeader.push(item.title);
        return item;
      })
      let option:any = {
        fileName:this.mode==="sum"?"用量汇总":"用量时间分段",
        datas:[
          {
            sheetData:datas,
            sheetName:"sheet",
            sheetFilter:sheetFilter,
            sheetHeader:sheetHeader
          }
        ]
      }
      let toExcel = new ExportJsonExcel(option);
      toExcel.saveExcel();
    }
}

export default CalcCode;
